<template>
<basePages>	
  <view class="alert-container">
    <!-- 顶部标题栏 -->
    <view class="header">
      <image src="/static/emergency-icon.png" mode="aspectFit" class="logo"></image>
      <text class="title">紧急报警 - {{ userName }}</text>
      <view class="badge" v-if="unreadCount > 0">
        <text>{{ unreadCount }}</text>
      </view>
    </view>

    <!-- 状态卡片 -->
    <view class="status-card">
      <view class="status-item">
        <text class="status-value">{{ criticalCount }}</text>
        <text class="status-label">紧急报警</text>
      </view>
      <view class="status-item">
        <text class="status-value">{{ warningCount }}</text>
        <text class="status-label">警告报警</text>
      </view>
      <view class="status-item">
        <text class="status-value">{{ normalCount }}</text>
        <text class="status-label">普通提醒</text>
      </view>
    </view>

    <!-- 选项卡 -->
    <view class="tabs">
      <view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', activeTab === index ? 'active' : '']"
        @click="activeTab = index">
        {{ tab }}
      </view>
    </view>

    <!-- 内容区 -->
    <scroll-view scroll-y class="content">
      <button class="add-btn" @click="simulateAlert">
        <uni-icons type="plus" size="16" color="#fff"></uni-icons>
        模拟报警
      </button>

      <view class="alert-list">
        <view v-for="alert in filteredAlerts" :key="alert.id" class="alert-card" :class="alert.type">
          <view class="card-header">
            <view class="alert-level">
              <uni-icons :type="alert.type === 'critical' ? 'alert' : 'info'"
                :color="alert.type === 'critical' ? '#f56c6c' : '#e6a23c'" size="16"></uni-icons>
              <text>{{ alert.type === 'critical' ? '紧急' : '警告' }}</text>
            </view>
            <text class="alert-time">{{ alert.time }}</text>
          </view>

          <view class="alert-content">
            <text class="alert-message">{{ alert.message }}</text>
            <view class="alert-meta">
              <text class="location">{{ alert.location }}</text>
              <text class="device">{{ alert.device }}</text>
            </view>
          </view>

          <view class="card-footer">
            <button class="action-btn" @click="viewDetail(alert)">查看详情</button>
            <button class="action-btn primary" @click="handleAlert(alert.id)">处理</button>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 详情弹窗 -->
    <uni-popup ref="detailDialog" type="dialog">
      <uni-popup-dialog mode="base" :title="currentAlert.level === 'critical' ? '紧急报警详情' : '报警详情'">
        <view class="dialog-content">
          <view class="detail-item">
            <text class="detail-label">报警时间:</text>
            <text class="detail-value">{{ currentAlert.time }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">报警内容:</text>
            <text class="detail-value">{{ currentAlert.message }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">发生位置:</text>
            <text class="detail-value">{{ currentAlert.location }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">触发者:</text>
            <text class="detail-value">{{ currentAlert.device }}</text>
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </view>
 </basePages> 
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAlertStore } from '../../store/modules/useAlertStore.js'
import { useUserStore } from '../../store/modules/useUserStore.js'
import { useBindingStore } from '../../store/modules/useBindingStore.js'


import { get, post } from '@/utils/request.js'
const userStore=useUserStore()
const bindingStore = useBindingStore()
const alertStore = useAlertStore()


const userName = ref('userName--')


const activeTab = ref(0)
const tabs = ref(['全部消息', '紧急报警', '警告提醒'])



// 计算属性保持不变
const unreadCount = computed(() => alertStore.getAlertList?.length)
const criticalCount = computed(() => alertStore.getAlertList?.filter(a => a.type === 'critical').length)
const warningCount = computed(() => alertStore.getAlertList?.filter(a => a.type === 'warning').length)
const normalCount = computed(() => alertStore.getAlertList?.filter(a => a.type === 'normal').length)

// 计算属性修改
const filteredAlerts = computed(() => {
  if (activeTab.value === 0) return alertStore.getAlertList
  if (activeTab.value === 1) return alertStore.getAlertList?.filter(a => a.type === 'critical')
  return alertStore.getAlertList.filter(a => a.type === 'warning')
})

const currentAlert = ref({})
const detailDialog = ref(null)

const viewDetail = (alert) => {
  currentAlert.value = alert
  detailDialog.value.open()
}

// 处理警报（调用 store 方法）
const handleAlert = async (id) => {
  console.log('handleAlert:', id)
  try {
    const result = await alertStore.resolveAlert(id)

    if (result?.code === 200) {
      uni.showToast({
        title: '已处理',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: result?.msg || '处理失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('handleAlert error:', error)
  }
}

// 模拟警报（调用 store 方法）
const simulateAlert = async () => {
  const alertTypes = {
    0: ['critical', 'warning', 'normal'][Math.floor(Math.random() * 3)],
    1: 'critical',
    2: 'warning'
  }
  const alertMessages = {
    critical: [
      '老人突然跌倒！',
      '心率异常升高！',
      '血压异常升高！',
      '长时间未活动！'
    ],
    warning: [
      '老人已经入睡',
      '老人午睡醒来',
      '老人外出散步',
      '老人用餐时间'
    ],
    normal: [
      '老人正常活动',
      '老人按时服药',
      '老人正常作息'
    ]
  }

  const alertLocations = ['卧室', '客厅', '卫生间', '厨房', '阳台']
  const alertDevices = ['智能手环', '智能床垫', '智能摄像头', '门磁传感器', '用户', '其他']

  const level = alertTypes[activeTab.value]
  const newAlert = {
    type: level,  // 直接使用level值
    location: alertLocations[Math.floor(Math.random() * alertLocations.length)],
    description: alertMessages[level][Math.floor(Math.random() * alertMessages[level].length)],
    triggeror: alertDevices[Math.floor(Math.random() * alertDevices.length)],
    userId: alertStore.getAlertUserId
  }

  try {
    
    const result = await alertStore.triggerAlert(newAlert)

    console.log('triggleAlert res: ',result)
    if (result && result.code === 200) {
      uni.showToast({
        title: `已添加${level === 'critical' ? '紧急' : level === '警告' ? '警告' : '普通'}报警`,
        icon: 'success'
      })
    } else if (result) {
      throw new Error("触发报警失败", result.msg)
    } else {
      throw new Error("触发报警失败")
    }
  } catch (err) {
    uni.showToast({
      title: err.message || '触发失败',
      icon: 'none'
    })
  }
}

// 模拟WebSocket连接
const setupWebSocket = () => {
  setInterval(async () => {
    if (Math.random() > 0.8) {
      await simulateAlert()
    }
  }, 10000)
}

onMounted(async () => {
  const userStore=useUserStore()
  const bindingStore = useBindingStore()
  const alertStore = useAlertStore()
  try {
    const role_= userStore.getUserData.role
    if(role_ == 'older'){
      alertStore.setAlertUserId(userStore.curUserId)
      userName.value = userStore.getUserData.name || '老人'
    }else{
      console.log('bindingStore.getCurBindingId',bindingStore.getCurBindingId)
      alertStore.setAlertUserId(bindingStore.getCurBindingId)
      userName.value = bindingStore?.getBindingList?.find(item => item.id === bindingStore.getCurBindingId)?.name || '老人'

      console.log('alertuserId',alertStore.getAlertUserId)
    }

    

    const result = await alertStore.fetchAlerts()

    if (result && result?.code !== 200) {
      uni.showToast({
        title: result.msg || '初始化失败',
        icon: 'none'
      })
    }

  } catch (err) {
    console.log(err)
  }

  // setupWebSocket()
})
</script>

<style lang="scss" scoped>
.alert-container {
  padding: 20rpx;
  background-color: #f8fafc;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx 0;

  .logo {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
  }

  .title {
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
  }

  .badge {
    margin-left: auto;
    background-color: #f56c6c;
    color: white;
    border-radius: 20rpx;
    padding: 4rpx 12rpx;
    font-size: 24rpx;
  }
}

.status-card {
  display: flex;
  justify-content: space-between;
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin: 20rpx 0;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

  .status-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    .status-value {
      font-size: 40rpx;
      font-weight: bold;
      color: #409eff;

      &:first-child {
        color: #f56c6c;
      }
    }

    .status-label {
      font-size: 24rpx;
      color: #999;
      margin-top: 8rpx;
    }
  }
}

.tabs {
  display: flex;
  background: #fff;
  border-radius: 12rpx;
  margin: 20rpx 0;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 30rpx;
    color: #666;

    &.active {
      color: #409eff;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 80rpx;
        height: 6rpx;
        background: #409eff;
        border-radius: 3rpx;
      }
    }
  }
}

.content {
  padding-bottom: 40rpx;
}

.add-btn {
  background: #409eff;
  color: #fff;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  font-size: 28rpx;

  uni-icons {
    margin-right: 10rpx;
  }
}

.alert-list {
  .alert-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

    &.critical {
      border-left: 8rpx solid #f56c6c;
    }

    &.warning {
      border-left: 8rpx solid #e6a23c;
    }

    &.normal {
      border-left: 8rpx solid #409eff;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .alert-level {
        display: flex;
        align-items: center;

        text {
          margin-left: 10rpx;
          font-size: 28rpx;
          font-weight: 500;
        }
      }

      .alert-time {
        color: #999;
        font-size: 26rpx;
      }
    }

    .alert-content {
      .alert-message {
        font-size: 30rpx;
        color: #333;
        margin-bottom: 16rpx;
        line-height: 1.5;
      }

      .alert-meta {
        display: flex;
        font-size: 26rpx;
        color: #999;
        margin-bottom: 24rpx;

        .location {
          margin-right: 20rpx;
        }
      }
    }

    .card-footer {
      display: flex;
      justify-content: flex-end;
      padding-top: 20rpx;
      border-top: 1rpx solid #eee;

      .action-btn {
        margin-left: 20rpx;
        font-size: 26rpx;
        padding: 12rpx 24rpx;
        border-radius: 8rpx;
        background: #f0f7ff;
        color: #409eff;

        &.primary {
          background: #409eff;
          color: white;
        }

        &:active {
          opacity: 0.8;
        }
      }
    }
  }
}

.dialog-content {
  .detail-item {
    display: flex;
    margin-bottom: 20rpx;

    .detail-label {
      width: 120rpx;
      color: #666;
      font-size: 28rpx;
    }

    .detail-value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
  }
}
</style>